package com.sense.kukoo.common.repo.http

import com.google.gson.Gson
import com.sense.kukoo.common.constant.ConstantConfig
import com.sense.kukoo.common.utils.AppConfig
import okhttp3.Dispatcher
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class KukooHttpManager {
    companion object {

        val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { KukooHttpManager() }

        fun createRequestBody(map: HashMap<String, Any>): RequestBody{
            val json = Gson().toJson(map)
            return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json)
        }

    }

    val mClient: OkHttpClient

    init {
        val builder = OkHttpClient.Builder()
        val dispatcher = Dispatcher()
        dispatcher.maxRequests = 500000
        dispatcher.maxRequestsPerHost = 100000
        builder.connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .addInterceptor(KukooInterceptor.instance)
            .retryOnConnectionFailure(true)
            .dispatcher(dispatcher)
        mClient = builder.build()
    }

    fun <T> createHttpClient(service: Class<T>): T {
        //
        val retrofitHttpApi = Retrofit.Builder()
            .baseUrl(ConstantConfig.URL.baseUrl())
            .addConverterFactory(GsonConverterFactory.create())
            .client(mClient)
            .build()
            .create(service)
        return retrofitHttpApi
    }


}